package com.tjhzzx.ibmsSupervisor.command;

import com.tjhzzx.ibmsSupervisor.history.HistoryManager;
import com.tjhzzx.ibmsSupervisor.history.entities.HistoryDataItem;
import com.tjhzzx.ibmsSupervisor.history.entities.HistoryDataMessage;
import com.tjhzzx.ibmsSupervisor.history.entities.HistoryDataUnit;
import com.tjhzzx.ibmsSupervisor.servlet.AbstractServletCommand;
import com.tjhzzx.ibmsSupervisor.servlet.JSONResult;
import com.tridium.json.JSONObject;
import org.apache.commons.lang3.StringUtils;

import javax.baja.web.WebOp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

public class HistorySearchCommand extends AbstractServletCommand {
    private static final Logger LOGGER = Logger.getLogger(HistorySearchCommand.class.getName());

    public void postHistoryRecords(WebOp op, String queryString) throws Exception {
        Map<String, Object> params = resolveParams(queryString);
        String historyIds = (String) params.get("h");
        if(StringUtils.isBlank(historyIds)) {
            return;
        }
        String[] historyIdArray = historyIds.split("\\|\\|\\|");
        HistoryDataMessage request = new HistoryDataMessage();
        request.startTime = (String) params.get("start");
        request.endTime = (String) params.get("end");
        List<HistoryDataItem> items = new ArrayList<>();
        for(String historyId : historyIdArray) {
            String[] history = historyId.split("\\|\\|");
            if(history != null && history.length == 2 && StringUtils.isNotBlank(history[0])
                    && StringUtils.isNotBlank(history[1])) {
                HistoryDataItem historyDataItem = new HistoryDataItem();
                historyDataItem.name = history[0];
                historyDataItem.ord = history[1].replace("history:", "");
                items.add(historyDataItem);
            }
        }
        request.items = items;
        HistoryDataMessage result = HistoryManager.searchHistoryData(request);
        jsonResponse(result);
    }

    public void getHistoryTableData(WebOp op, String queryString) throws Exception {
        Map<String, Object> params = resolveParams(queryString);
        String historyId = (String) params.get("h");
        if(historyId == null || "".equals(historyId)) {
            return;
        }
        String[] history = historyId.split("\\|\\|");
        HistoryDataItem historyDataItem = new HistoryDataItem();
        historyDataItem.name = history[0];
        historyDataItem.ord  = history[1].replace("history:", "");
        List<HistoryDataItem> items = new ArrayList<>();
        items.add(historyDataItem);
        HistoryDataMessage request = new HistoryDataMessage();
        request.startTime = (String) params.get("start");
        request.endTime = (String) params.get("end");
        request.items = items;
        HistoryDataMessage result = HistoryManager.searchHistoryData(request);
        JSONObject pageResult = new JSONObject();
        long page = Long.parseLong((String) params.get("page"));
        long rows = Long.parseLong((String) params.get("rows"));
        if(result != null && result.items != null && result.items.size()>0
                && result.items.get(0).units != null
                && result.items.get(0).units.size()>0) {
            List<HistoryDataUnit> units = result.items.get(0).units;
            long totalRecord = units.size();
            long totalPage = totalRecord % rows == 0 ? totalRecord / rows : totalRecord / rows + 1;
            long index = (page - 1) * rows;
            long pageSize = rows;
            List<JSONObject> jsonObjects = new ArrayList<>();
            for (long i = index; i < index + pageSize && i < units.size(); i++) {
                HistoryDataUnit unit = units.get((int) i);
                JSONObject row = new JSONObject();
                row.put("id", i+1);
                row.put("cell", new String[]{String.valueOf(i+1), unit.time, unit.value});
                jsonObjects.add(row);
            }
            pageResult.put("page", page);
            pageResult.put("total", totalPage);
            pageResult.put("records", totalRecord);
            pageResult.put("rows", jsonObjects);
        }
        setResponse(pageResult.toString());
    }

    public void postHistoryData2(WebOp op, String queryString) throws Exception {
//        LOGGER.info("postHistoryData2() queryString: " + queryString);
        JSONResult pageResult = new JSONResult();
        Map<String, Object> params = resolveParams(queryString);
        String historyIds = (String) params.get("h");
        if(StringUtils.isBlank(historyIds)) {
            jsonResponse(JSONResult.error("历史查询参数'historyId'配置错误"));
            return;
        }
        List<JSONObject> datas = new ArrayList<>();
        String[] historyIdArray = historyIds.split("\\|\\|\\|");
        for(String historyId : historyIdArray) {
            String[] history = historyId.split("\\|\\|");
            HistoryDataItem historyDataItem = new HistoryDataItem();
            historyDataItem.name = history[0];
            historyDataItem.ord  = history[1].replace("history:", "");
            List<HistoryDataItem> items = new ArrayList<>();
            items.add(historyDataItem);
            HistoryDataMessage request = new HistoryDataMessage();
            request.startTime = (String) params.get("start");
            request.endTime = (String) params.get("end");
            request.items = items;
            HistoryDataMessage result = HistoryManager.searchHistoryData(request);
//            LOGGER.info("postHistoryData() result: " + result);
            long pageNo = Long.parseLong((String) params.get("pageNo"));
            long pageSize = Long.parseLong((String) params.get("pageSize"));
            if(result != null && result.items != null && result.items.size()>0
                    && result.items.get(0).units != null
                    && result.items.get(0).units.size()>0) {
                List<HistoryDataUnit> units = result.items.get(0).units;
                long total = units.size();
                if(pageNo == -1) {
                    pageSize = total;
                    pageNo = 1;
                }
//                long totalPage = total % pageSize == 0 ? total / pageSize : total / pageSize + 1;
                long index = (pageNo - 1) * pageSize;
                List<JSONObject> list = new ArrayList<>();
                for (long i = index; i < index + pageSize && i < units.size(); i++) {
                    HistoryDataUnit unit = units.get((int) i);
                    JSONObject row = new JSONObject();
                    row.put("id", i+1);
                    row.put("time", unit.time);
                    row.put("value", unit.value);
                    list.add(row);
                }
                JSONObject data = new JSONObject();
                data.put("ord", result.items.get(0).ord);
                data.put("name", result.items.get(0).name);
                data.put("total", total);
                data.put("list", list);
                datas.add(data);
            }
        }
        jsonResultResponse(JSONResult.success("查询成功").add("datas", datas));
    }
}
